const request = require('../../utils/request')
const { processImageUrl } = require('../../utils/imageUrl')
const platform = require('../../utils/platform')
const eventBus = require('../../utils/eventBus')
const BasePage = require('../base')
const app = getApp()

Page(BasePage({
  data: {
    bannerList: [],
    courseList: [],
    categoryOptions: [],
    pageNum: 1,
    pageSize: 6,
    isLoading: false,
    noMoreData: false,
    currentFilter: '',
    showFilterPopup: false,
    selectedCategory: '全部课程',
    selectedTime: '全部时间',
    selectedTeacher: '全部讲师',
    timeOptions: [
      { label: '全部时间', value: '', selected: true },
      { label: '工作日', value: 'weekday', selected: false },
      { label: '周末', value: 'weekend', selected: false },
      { label: '晚上', value: 'evening', selected: false }
    ],
    teacherOptions: [],
    tempSelectedOptions: {
      category: '',
      time: '',
      teacher: ''
    },
    filterParams: {
      category: '',
      time: '',
      teacher: ''
    },
    searchTimer: null,
    searchKeyword: '',
    windowHeight: 0,
    windowWidth: 0,
    isEmpty: false,
    platformInfo: {},
    isLoggedIn: false,
    userInfo: null,
    showLoginBtn: false,
    userPoints: 0,
    scrollTop: 0,
    showAIAssistant: false,
    tempShowAssistant: false,
    aiAssistantComponentRefresh: false,
    showQuickServiceMenu: false  // 快捷服务菜单显示状态
  },

  onLoad() {
    const windowInfo = wx.getWindowInfo()
    
    const platformInfo = platform.getPlatformInfo();
    
    this.setData({
      windowHeight: windowInfo.windowHeight,
      windowWidth: windowInfo.windowWidth,
      platformInfo
    })
    
    // 在安卓设备上，延迟设置scrollTop确保滚动正常
    if (platformInfo.isAndroid) {
      setTimeout(() => {
        this.setData({ scrollTop: 1 });
        setTimeout(() => {
          this.setData({ scrollTop: 0 });
        }, 50);
      }, 100);
    }
    
    // 从app.js获取登录状态
    if (app.globalData.isLoggedIn && app.globalData.userInfo) {
      this.setData({
        isLoggedIn: true,
        userInfo: app.globalData.userInfo,
        showLoginBtn: false,
        userPoints: app.globalData.userInfo.availablePoints || 0
      });
    } else {
      // 如果全局状态中没有登录信息，检查本地token
      this.checkLoginStatus();
    }
    
    this.fetchHomeData()
    this.fetchTeachers()
    
    console.log('当前平台:', platformInfo);
    
    // 监听显示登录按钮的事件
    eventBus.on('show-login-modal', this.handleShowLoginModal.bind(this));
    
    // 监听积分更新事件，实时更新首页显示的积分
    eventBus.on('pointsUpdate', this.updateUserPoints.bind(this));
    
    // 确保AI助手按钮初始状态正确
    this.resetAIAssistant();
  },
  
  // 页面卸载时移除事件监听
  onUnload() {
    eventBus.off('show-login-modal', this.handleShowLoginModal);
    eventBus.off('pointsUpdate', this.updateUserPoints);
  },
  
  // 处理TabBar点击事件
  onTabItemTap(item) {
    console.log('TabBar点击事件 - 首页:', item);
    // 当用户在当前页面再次点击TabBar时，重置状态
    if (this.data.showAIAssistant) {
      this.resetAIAssistant();
    }
    
    // 滚动到顶部
    this.scrollToTop();
  },
  
  // 添加更新用户积分的方法
  async updateUserPoints() {
    if (!this.data.isLoggedIn) return;
    
    try {
      const userId = app.globalData.userInfo?.id;
      if (!userId) return;
      
      const response = await request({
        url: '/api/points/overview',
        data: { userId }
      });
      
      if (response.code === 200) {
        // 更新首页显示的用户积分
        const userInfo = {...this.data.userInfo, availablePoints: response.data.availablePoints};
        this.setData({ userInfo });
        
        // 同时更新全局状态中的用户积分
        app.globalData.userInfo.availablePoints = response.data.availablePoints;
      }
    } catch (error) {
      console.error('更新积分信息失败:', error);
    }
  },
  
  // 处理显示登录模态框的事件
  handleShowLoginModal() {
    this.setData({ showLoginBtn: true });
    
    // 显示登录提示
    wx.showModal({
      title: '提示',
      content: '请先登录后使用此功能',
      confirmText: '立即登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.handleWechatLogin();
        }
      }
    });
  },
  
  // 页面显示时检查登录状态和修复滚动
  onShow() {
    console.log('首页显示 - 时间:', new Date().toLocaleTimeString());
    
    if (app.globalData.isLoggedIn !== this.data.isLoggedIn) {
      this.setData({
        isLoggedIn: app.globalData.isLoggedIn,
        userInfo: app.globalData.userInfo,
        showLoginBtn: !app.globalData.isLoggedIn,
        userPoints: app.globalData.userInfo?.availablePoints || 0
      });
    }
    
    // 重置AI助手状态
    if (this.data.showAIAssistant) {
      console.log('页面切换后重置AI助手状态');
      this.setData({ showAIAssistant: false });
    }
    
    // 安卓滚动修复
    if (this.data.platformInfo && this.data.platformInfo.isAndroid) {
      // 延迟一下再触发滚动修复，确保页面已经完全渲染
      setTimeout(() => {
        this.setData({ scrollTop: 0 });
      }, 300);
    }
    
    // 确保组件被正确创建
    // 延迟一点时间以让页面完全加载
    setTimeout(() => {
      this.setData({
        aiAssistantComponentRefresh: true
      }, () => {
        setTimeout(() => {
          this.setData({
            aiAssistantComponentRefresh: false
          });
          console.log('AI助手组件已刷新');
        }, 100);
      });
    }, 200);
  },
  
  // 添加隐藏页面时的处理
  onHide() {
    // 确保离开页面时AI助手被关闭
    if (this.data.showAIAssistant) {
      // 记录当前状态以便返回时还原
      console.log('页面离开时关闭AI助手');
      this.setData({
        showAIAssistant: false
      });
    }
  },
  
  // 响应用户登录事件
  onUserLogin(userInfo) {
    this.setData({
      isLoggedIn: true,
      userInfo: userInfo,
      showLoginBtn: false
    });
  },
  
  // 响应用户登出事件
  onUserLogout() {
    this.setData({
      isLoggedIn: false,
      userInfo: null,
      showLoginBtn: true
    });
  },

  // 添加检查登录状态的方法
  async checkLoginStatus() {
    try {
      const token = wx.getStorageSync('token')
      if (!token) {
        this.setData({ showLoginBtn: true })
        return
      }
      
      const result = await request({
        url: '/api/login/check',
        data: { token }
      })
      
      if (result.code === 200 && result.data.isLoggedIn) {
        // 处理头像URL
        if (result.data.user && result.data.user.avatar) {
          result.data.user.avatar = processImageUrl(result.data.user.avatar);
        }
        
        this.setData({
          isLoggedIn: true,
          userInfo: result.data.user,
          showLoginBtn: false
        })
        
        // 通知应用全局状态
        app.globalData.isLoggedIn = true;
        app.globalData.userInfo = result.data.user;
        
        // 触发登录事件
        eventBus.emit('user-login', result.data.user);
      } else {
        // 登录已过期，清除本地token
        wx.removeStorageSync('token')
        this.setData({ showLoginBtn: true })
      }
    } catch (error) {
      console.error('检查登录状态失败:', error)
      this.setData({ showLoginBtn: true })
    }
  },
  
  // 添加微信登录方法
  handleWechatLogin() {
    wx.showLoading({ title: '登录中...' })
    
    wx.login({
      success: async (res) => {
        if (res.code) {
          try {
            const loginResult = await request({
              url: '/api/login/wechat',
              method: 'POST',
              data: { code: res.code }
            })
            
            if (loginResult.code === 200) {
              // 登录成功，保存token
              wx.setStorageSync('token', loginResult.data.token)
              
              // 处理头像URL
              if (loginResult.data.user && loginResult.data.user.avatar) {
                loginResult.data.user.avatar = processImageUrl(loginResult.data.user.avatar);
              }
              
              this.setData({
                isLoggedIn: true,
                userInfo: loginResult.data.user,
                showLoginBtn: false
              })
              
              // 更新全局状态
              app.globalData.isLoggedIn = true;
              app.globalData.userInfo = loginResult.data.user;
              
              // 触发登录事件
              eventBus.emit('user-login', loginResult.data.user);
              
              wx.showToast({
                title: '登录成功',
                icon: 'success'
              })
            } else {
              wx.showToast({
                title: '登录失败',
                icon: 'none'
              })
            }
          } catch (error) {
            console.error('微信登录失败:', error)
            wx.showToast({
              title: '登录失败',
              icon: 'none'
            })
          }
        } else {
          wx.showToast({
            title: '获取微信授权失败',
            icon: 'none'
          })
        }
        wx.hideLoading()
      }
    })
  },
  
  // 退出登录方法
  async handleLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const token = wx.getStorageSync('token')
            await request({
              url: '/api/login/logout',
              method: 'POST',
              data: { token }
            })
            
            // 清除本地存储
            wx.removeStorageSync('token')
            
            this.setData({
              isLoggedIn: false,
              userInfo: null,
              showLoginBtn: true
            })
            
            // 更新全局状态
            app.globalData.isLoggedIn = false;
            app.globalData.userInfo = null;
            
            // 触发登出事件
            eventBus.emit('user-logout');
            
            wx.showToast({
              title: '已退出登录',
              icon: 'success'
            })
          } catch (error) {
            console.error('退出登录失败:', error)
            wx.showToast({
              title: '退出失败',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  getPlatformClass(className) {
    return platform.getPlatformClass(className);
  },

  // 获取讲师列表
  async fetchTeachers() {
    try {
      const res = await request({
        url: '/api/teachers'
      })
      
      const teacherOptions = (res.data || []).map(item => ({
        label: item.name,
        value: item.id.toString(),
        selected: false
      }))
      teacherOptions.unshift({ label: '全部讲师', value: '', selected: true })
    
      this.setData({
        teacherOptions: teacherOptions
      })
    } catch (error) {
      // 如果是成功响应但被当作错误处理的情况
      if (error && error.code === 0 && Array.isArray(error.data)) {
        const teacherOptions = error.data.map(item => ({
          label: item.name,
          value: item.id.toString(),
          selected: false
        }))
        teacherOptions.unshift({ label: '全部讲师', value: '', selected: true })
        
        this.setData({
          teacherOptions: teacherOptions
        })
        return
      }
      
      wx.showToast({
        title: '获取讲师列表失败',
        icon: 'none'
      })
      console.error('获取讲师列表失败:', error)
    }
  },  // 添加逗号

  async fetchHomeData() {
    try {
      const { data } = await request({
        url: '/api/home',
        data: {
          page: this.data.pageNum,
          limit: this.data.pageSize,
          category: this.data.filterParams.category || '',
          teacher: this.data.filterParams.teacher || '',
          time: this.data.filterParams.time || '',
          keyword: this.data.filterParams.keyword
        }
      })

      // 处理轮播图数据
      const banners = (data.banners || []).map(banner => ({
        ...banner,
        image_url: processImageUrl(banner.image_url)
      }))

      // 处理课程数据
      const recommendCourses = (data.recommendCourses || []).map(course => ({
        ...course,
        image_url: processImageUrl(course.image_url),
        teacher_avatar: processImageUrl(course.teacher_avatar)
      }))

      // 处理分类数据（基于name去重）
      if (this.data.pageNum === 1) {  // 只在第一页时更新分类选项
        // 按name分组并保留最小id的记录
        const categoryMap = {}
        data.categories?.forEach(item => {
          if (!categoryMap[item.name] || categoryMap[item.name].id > item.id) {
            categoryMap[item.name] = item
          }
        })

        // 转换为数组
        const uniqueCategories = Object.values(categoryMap)

        // 按sort字段排序并生成选项
        const categoryOptions = uniqueCategories
          .sort((a, b) => a.sort - b.sort)
          .map(item => ({
            label: item.name,
            value: item.id.toString(),
            selected: this.data.filterParams.category === item.id.toString()
          }))

        // 添加"全部课程"选项
        categoryOptions.unshift({ 
          label: '全部课程', 
          value: '', 
          selected: !this.data.filterParams.category 
        })

        this.setData({ categoryOptions })
      }

      this.setData({
        bannerList: banners,
        courseList: this.data.pageNum === 1 ? recommendCourses : [...this.data.courseList, ...recommendCourses],
        noMoreData: recommendCourses.length < this.data.pageSize,
        isEmpty: this.data.pageNum === 1 && recommendCourses.length === 0
      }, () => {
        // 在数据更新后触发一次滚动修复（仅安卓设备）
        if (this.data.platformInfo.isAndroid) {
          setTimeout(() => {
            const currentScrollTop = this.data.scrollTop;
            this.setData({ scrollTop: currentScrollTop + 1 });
            setTimeout(() => {
              this.setData({ scrollTop: currentScrollTop });
            }, 50);
          }, 300);
        }
      })
    } catch (error) {
      console.error('获取首页数据失败:', error)
    }
  },

  // 加载更多课程
  async onLoadMore() {
    if (this.data.isLoading || this.data.noMoreData) return

    this.setData({ isLoading: true })
    
    try {
      const { data } = await request({
        url: '/api/home',
        data: {
          page: this.data.pageNum + 1,
          limit: this.data.pageSize,
          ...this.data.filterParams
        }
      })

      // 处理新加载的课程数据
      const newCourses = (data.recommendCourses || []).map(course => ({
        ...course,
        image_url: processImageUrl(course.image_url),
        teacher_avatar: processImageUrl(course.teacher_avatar)
      }))

      this.setData({
        courseList: [...this.data.courseList, ...newCourses],
        pageNum: this.data.pageNum + 1,
        isLoading: false,
        noMoreData: newCourses.length < this.data.pageSize
      })
    } catch (error) {
      console.error('加载更多课程失败:', error)
      this.setData({ isLoading: false })
    }
  },

  // 添加搜索输入处理方法
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  // 修改搜索处理方法
  async onSearch() {
    if (this.data.searchTimer) {
      clearTimeout(this.data.searchTimer)
    }

    const keyword = this.data.searchKeyword ? this.data.searchKeyword.trim() : '';
    
    // 添加埋点：记录搜索事件
    if (keyword) {
      this.trackEvent('search_courses', {
        keyword: keyword
      });
    }

    const timer = setTimeout(async () => {
      this.setData({
        pageNum: 1,
        courseList: [],
        noMoreData: false,
        filterParams: {
          ...this.data.filterParams,
          keyword: keyword
        }
      }, async () => {
        await this.fetchHomeData()
      })
    }, 500)

    this.setData({ searchTimer: timer })
  },

  // 筛选确认
  async confirmFilter() {
    const currentFilter = this.data.currentFilter
    const selectedValue = this.data.tempSelectedOptions[currentFilter]
    
    // 添加埋点：记录筛选事件
    let filterLabel = '';
    if (currentFilter === 'category') {
      const selectedOption = this.data.categoryOptions.find(item => item.value === selectedValue);
      filterLabel = selectedOption ? selectedOption.label : '';
    } else if (currentFilter === 'time') {
      const selectedOption = this.data.timeOptions.find(item => item.value === selectedValue);
      filterLabel = selectedOption ? selectedOption.label : '';
    } else if (currentFilter === 'teacher') {
      const selectedOption = this.data.teacherOptions.find(item => item.value === selectedValue);
      filterLabel = selectedOption ? selectedOption.label : '';
    }
    
    if (selectedValue) {
      this.trackEvent('filter_courses', {
        filter_type: currentFilter,
        filter_value: selectedValue,
        filter_label: filterLabel
      });
    }
    
    // 更新选中项的显示和筛选参数
    let updateData = {
      [`filterParams.${currentFilter}`]: selectedValue || '',
      showFilterPopup: false,
      currentFilter: '',
      pageNum: 1,
      courseList: [],
      noMoreData: false
    }

    if (currentFilter === 'category') {
      const selectedOption = this.data.categoryOptions.find(item => item.value === selectedValue)
      updateData.selectedCategory = selectedOption ? selectedOption.label : ''
    } else if (currentFilter === 'time') {
      const selectedOption = this.data.timeOptions.find(item => item.value === selectedValue)
      updateData.selectedTime = selectedOption ? selectedOption.label : ''
    } else if (currentFilter === 'teacher') {
      const selectedOption = this.data.teacherOptions.find(item => item.value === selectedValue)
      updateData.selectedTeacher = selectedOption ? selectedOption.label : ''
    }

    this.setData(updateData, async () => {
      await this.fetchHomeData()
    })
  },
  // 跳转到课程详情页
  navigateToCourseDetail(e) {
    const courseId = e.currentTarget.dataset.id;
    const courseTitle = e.currentTarget.dataset.title || '';
    
    // 添加埋点：记录课程点击事件
    this.trackEvent('course_item_click', {
      course_id: courseId,
      course_title: courseTitle
    });
    
    // 检查用户是否已登录
    if (!this.data.isLoggedIn) {
      wx.showModal({
        title: '提示',
        content: '请先登录后查看课程详情',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 用户点击"去登录"按钮，触发登录流程
            this.handleWechatLogin();
          }
        }
      });
      return;
    }
    
    // 已登录用户正常跳转
    wx.navigateTo({
      url: `/packageA/course-detail/index?id=${courseId}`,
      fail: (err) => {
        console.error('页面跳转失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },
  // 显示筛选弹窗
  showFilter(e) {
    const filterType = e.currentTarget.dataset.type
    
    // 根据当前筛选参数更新选项的选中状态
    if (filterType === 'category') {
      const newOptions = this.data.categoryOptions.map(item => ({
        ...item,
        selected: item.value === this.data.filterParams.category
      }))
      this.setData({ categoryOptions: newOptions })
    } else if (filterType === 'time') {
      const newOptions = this.data.timeOptions.map(item => ({
        ...item,
        selected: item.value === this.data.filterParams.time
      }))
      this.setData({ timeOptions: newOptions })
    } else if (filterType === 'teacher') {
      const newOptions = this.data.teacherOptions.map(item => ({
        ...item,
        selected: item.value === this.data.filterParams.teacher
      }))
      this.setData({ teacherOptions: newOptions })
    }

    // 设置临时选中状态
    this.setData({
      showFilterPopup: true,
      currentFilter: filterType,
      [`tempSelectedOptions.${filterType}`]: this.data.filterParams[filterType] || ''
    })
  },

  // 隐藏筛选弹窗
  hideFilter() {
    this.setData({
      showFilterPopup: false,
      currentFilter: ''
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 选择筛选选项
  selectOption(e) {
    const value = e.currentTarget.dataset.value
    const currentFilter = this.data.currentFilter
    
    // 更新临时选中状态
    this.setData({
      [`tempSelectedOptions.${currentFilter}`]: value
    })

    // 更新选项的选中状态
    if (currentFilter === 'category') {
      const newOptions = this.data.categoryOptions.map(item => ({
        ...item,
        selected: item.value === value
      }))
      this.setData({ categoryOptions: newOptions })
    } else if (currentFilter === 'time') {
      const newOptions = this.data.timeOptions.map(item => ({
        ...item,
        selected: item.value === value
      }))
      this.setData({ timeOptions: newOptions })
    } else if (currentFilter === 'teacher') {
      const newOptions = this.data.teacherOptions.map(item => ({
        ...item,
        selected: item.value === value
      }))
      this.setData({ teacherOptions: newOptions })
    }
  },

  // 重置筛选
  resetFilter() {
    const currentFilter = this.data.currentFilter
    
    // 重置对应的选项
    if (currentFilter === 'category') {
      const newOptions = this.data.categoryOptions.map(item => ({
        ...item,
        selected: item.value === ''
      }))
      this.setData({ 
        categoryOptions: newOptions,
        selectedCategory: ''
      })
    } else if (currentFilter === 'time') {
      const newOptions = this.data.timeOptions.map(item => ({
        ...item,
        selected: item.value === ''
      }))
      this.setData({ 
        timeOptions: newOptions,
        selectedTime: ''
      })
    } else if (currentFilter === 'teacher') {
      const newOptions = this.data.teacherOptions.map(item => ({
        ...item,
        selected: item.value === ''
      }))
      this.setData({ 
        teacherOptions: newOptions,
        selectedTeacher: ''
      })
    }

    // 重置临时选中状态
    this.setData({
      [`tempSelectedOptions.${currentFilter}`]: ''
    })
  },

  // 添加滚动到顶部方法，用于修复滚动问题
  scrollToTop() {
    this.setData({ scrollTop: 0 });
  },

  // 切换AI助手显示状态
  toggleAIAssistant() {
    console.log('AI助手按钮被点击，当前状态:', this.data.showAIAssistant);
    
    // 添加埋点：记录AI助手点击事件
    this.trackEvent('ai_assistant_toggle', {
      previous_state: this.data.showAIAssistant ? 'open' : 'closed',
      new_state: this.data.showAIAssistant ? 'closed' : 'open'
    });
    
    // 由于可能的组件重建，我们需要确保引用是最新的
    const currentPage = getCurrentPages().pop();
    
    // 如果当前状态是显示，则仅仅关闭
    if (this.data.showAIAssistant) {
      this.setData({ showAIAssistant: false });
      console.log('AI助手已关闭');
      return;
    }
    
    // 如果当前状态是关闭，需要确保组件存在后再打开
    // 使用一个强制刷新的方式来处理组件可能被移除的情况
    this.setData({ 
      aiAssistantComponentRefresh: true,
      showAIAssistant: false
    }, () => {
      // 短暂延迟后再次尝试打开组件
      setTimeout(() => {
        this.setData({
          aiAssistantComponentRefresh: false,
          showAIAssistant: true
        });
        console.log('AI助手已打开');
      }, 100);
    });
  },
  
  // 处理AI助手关闭事件
  onAIAssistantClose() {
    console.log('接收到AI助手关闭事件');
    this.setData({
      showAIAssistant: false
    });
  },

  // 添加重置AI助手状态的方法
  resetAIAssistant() {
    console.log('重置AI助手状态');
    // 使用延迟确保UI已经完全更新
    this.setData({ showAIAssistant: false }, () => {
      // 确保组件完全关闭后的延迟
      setTimeout(() => {
        // 这里可以添加其他重置逻辑
        console.log('AI助手状态已重置');
      }, 100);
    });
  },

  // 切换快捷服务菜单
  toggleQuickServiceMenu() {
    const newState = !this.data.showQuickServiceMenu;
    
    // 添加埋点：记录快捷服务菜单点击事件
    this.trackEvent('quick_service_toggle', {
      previous_state: this.data.showQuickServiceMenu ? 'open' : 'closed',
      new_state: newState ? 'open' : 'closed'
    });
    
    this.setData({
      showQuickServiceMenu: newState
    });
  },
  
  // 隐藏快捷服务菜单
  hideQuickServiceMenu() {
    this.setData({
      showQuickServiceMenu: false
    });
  },
  
  // 跳转到线下门店页面
  navigateToStores() {
    // 添加埋点：记录跳转到线下门店事件
    this.trackEvent('navigate_to_stores', {});
    
    this.hideQuickServiceMenu();
    wx.navigateTo({
      url: '/packageB/stores/index'
    });
  },
  
  // 跳转到积分商城页面
  navigateToPointsShop() {
    // 添加埋点：记录跳转到积分商城事件
    this.trackEvent('navigate_to_points_shop', {});
    
    this.hideQuickServiceMenu();
    wx.showToast({
      title: '积分商城即将上线',
      icon: 'none',
      duration: 2000
    });
  },
  
  // 跳转到意见反馈页面
  navigateToFeedback() {
    // 添加埋点：记录跳转到意见反馈事件
    this.trackEvent('navigate_to_feedback', {});
    
    this.hideQuickServiceMenu();
    wx.navigateTo({
      url: '/packageA/feedback/index'
    });
  },
  
  // 跳转到关于我们页面
  navigateToAbout() {
    // 添加埋点：记录跳转到关于我们事件
    this.trackEvent('navigate_to_about', {});
    
    this.hideQuickServiceMenu();
    wx.navigateTo({
      url: '/packageA/profile/index?section=about'
    });
  },

  // 添加轮播图点击方法
  handleBannerClick(e) {
    const bannerId = e.currentTarget.dataset.id;
    const bannerType = e.currentTarget.dataset.type || 'default';
    
    // 添加埋点：记录轮播图点击事件
    this.trackEvent('banner_click', {
      banner_id: bannerId,
      banner_type: bannerType
    });
    
    // 根据轮播图类型执行不同的跳转逻辑
    if (bannerType === 'advertisement') {
      // 跳转到广告页面
      wx.navigateTo({
        url: '/packageA/advertisement/index?source=banner&id=' + bannerId
      });
    } else if (bannerType === 'course' && e.currentTarget.dataset.courseId) {
      // 跳转到课程详情
      this.navigateToCourseDetail({
        currentTarget: {
          dataset: {
            id: e.currentTarget.dataset.courseId
          }
        }
      });
    }
  }
}))
